package pervasivePositioning.pos;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;

import android.location.Location;
import android.os.Environment;
import pervasivePositioning.androidPositioner.PositionService;
import pervasivePositioning.androidPositioner.Report;
import pervasivePositioning.androidPositioner.TCPPositionService;

public class PosHistory implements PositionService {

	private ArrayList<Report> history;
	private String filePath;
	private PositionService sendReceiver;
	
	public PosHistory() {
		reset();
		
		filePath = "download/positionservice.txt";
		filePath = "positionservice.txt";
	}

	public void setFilePath(String fp)
	{
		filePath = fp;
	}
	
	public void setSendReceiver(PositionService r) {
		sendReceiver = r;
	}
	
	@Override
	public void ReportPosition(long time, Coordinate position, Coordinate acceleration,
			String configValue) throws IOException {

			history.add(new Report(time, position, acceleration, configValue));
		
		// TODO Auto-generated method stub

	}

	@Override
	public void reset() {
		history = new ArrayList<Report>(20);		
	}

	@Override
	public void save() throws IOException {
		long seq = history.size() == 0 ? 0 : history.get(0).time;
		
		String fullFilePath = String.format("%s-%d.%s", filePath, seq, "txt");
		
	    File file = new File(Environment.getExternalStorageDirectory(), fullFilePath);
	    file.createNewFile();
	    FileWriter writer = new FileWriter(file, false);
	    
	    for (Report r : history) {
	    	writer.append(String.format("%d:\t%f\t%f;\t%f\t%f\t%f;\t%s\n",
	    			r.time,
	    			r.position.x, r.position.y,
	    			r.acceleration.x, r.acceleration.z, r.acceleration.z,
	    			r.configValue));
	    }
	    writer.close();
	}

	@Override
	public void send() throws IOException {
	    for (Report r : history) {
	    	sendReceiver.ReportPosition(r.time, r.position, r.acceleration, r.configValue);
	    }
	}
}
